package com.itheima.reggie.service.impl;

import com.fasterxml.jackson.databind.util.BeanUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.itheima.reggie.common.CustomException;
import com.itheima.reggie.entity.*;
import com.itheima.reggie.mapper.CategoryMapper;
import com.itheima.reggie.mapper.SetMealMapper;
import com.itheima.reggie.mapper.SetmealDishMapper;
import com.itheima.reggie.service.SetmealService;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class SetmealServiceImpl implements SetmealService {

    @Autowired(required = false)
    private SetMealMapper setMealMapper;

    @Autowired(required = false)
    private SetmealDishMapper setmealDishMapper;

    @Autowired(required = false)
    private CategoryMapper categoryMapper;

    @Override
    @CacheEvict(value = "setmealCache",allEntries = true)
    public void save(SetmealDto setmealDto) {
        //补全修改时间
        setmealDto.setUpdateTime(LocalDateTime.now());
        setmealDto.setCreateTime(LocalDateTime.now());

        //调用保存方法
        setMealMapper.save(setmealDto);

        //得到套餐得菜品,给所有得菜品补全信息（sermeal_id ,修改，创建时间,排序）
        List<SetmealDish> setmealDishes = setmealDto.getSetmealDishes();
        setmealDishes = setmealDishes.stream().map(setmealDish -> {
            setmealDish.setSetmealId(setmealDto.getId());
            setmealDish.setCreateTime(LocalDateTime.now());
            setmealDish.setUpdateTime(LocalDateTime.now());
            setmealDish.setCreateUser(setmealDto.getCreateUser());
            setmealDish.setUpdateUser(setmealDto.getUpdateUser());
            setmealDish.setSort(0);
            return setmealDish;
        }).collect(Collectors.toList());

        //批量插入菜品表
        setmealDishMapper.saveBatch(setmealDishes);
    }

    @Override
    public Page<SetmealDto> page(Integer page, Integer pageSize, String name) {
        //设置当前页与页面大小
        PageHelper.startPage(page,pageSize);
        //获取当前页数据
        List<Setmeal> setmealList = setMealMapper.findByName(name);
        //创建PageInfo
        PageInfo<Setmeal> pageInfo = new PageInfo<>(setmealList);

        List<SetmealDto> setmealDtos = new ArrayList<>();
        //把SetMeal转换成SetMealDto
        setmealDtos = setmealList.stream().map(setmeal -> {
            SetmealDto setmealDto = new SetmealDto();
            //拷贝属性
            BeanUtils.copyProperties(setmeal, setmealDto);

            //查找套餐类别
            Category category = categoryMapper.findById(setmeal.getCategoryId());

            setmealDto.setCategoryName(category.getName());
            return setmealDto;
        }).collect(Collectors.toList());

        //创建Page对象
        Page<SetmealDto> pageResult = new Page<>(setmealDtos,pageInfo.getTotal(),page,pageSize);
        return pageResult;
    }

    @Override
    @CacheEvict(value = "setmealCache",allEntries = true)
    public void deleteByIds(List<Long> ids) {
        //判断ids中是否存在在售菜品
        Long count = setMealMapper.queryDishWithStatus(ids);
        if (count>0){
            throw  new CustomException("存在套餐是在售状态,无法删除");
        }
        //如果删除套餐是停售状态，那么可以直接删除套餐
        setMealMapper.deleteByIds(ids);

        //删除套餐对应得套餐菜品
        setmealDishMapper.deleteBySetmealIds(ids);
    }

    @Override
    @Cacheable(value = "setmealCache",key = "#categoryId+'_'+#status")
    public List<Setmeal> list(Long categoryId, Integer status) {
        return setMealMapper.list(categoryId,status);
    }

    @Override
    public SetmealDto findById(Long id) {
        Setmeal setmeal = setMealMapper.findById(id);

        List<SetmealDish> setmealDishes= setmealDishMapper.findBySetmealId(id);

        SetmealDto setmealDto = new SetmealDto();
        BeanUtils.copyProperties(setmeal, setmealDto);

        setmealDto.setSetmealDishes(setmealDishes);

        return setmealDto;
    }

    @Override
    public void setStatus(Integer status, List<Long> ids) {
        setMealMapper.setStatus(status,ids);
    }

    @Override
    @Transactional
    public void update(SetmealDto setmealDto) {
        //修改套餐
        setMealMapper.update(setmealDto);

//        删除所有套餐内得菜品
        setmealDishMapper.deleteBySetmealId(setmealDto.getId());

        //获取所有得菜品
        List<SetmealDish> setmealDishes = setmealDto.getSetmealDishes();
        List<SetmealDish> setmealDishList = setmealDishes.stream().map(setmealDish -> {
            //对每一个元素加工
            setmealDish.setSetmealId(setmealDto.getId());
            setmealDish.setUpdateUser(setmealDto.getUpdateUser());
            setmealDish.setCreateUser(setmealDto.getCreateUser());
            setmealDish.setUpdateTime(LocalDateTime.now());
            setmealDish.setCreateTime(LocalDateTime.now());
            setmealDish.setSort(0);

            return setmealDish;
        }).collect(Collectors.toList());

        setmealDishMapper.saveBatch(setmealDishList);
    }


}
